package com.sam.mooc;

/**
 * 动态规划
 * 最长公共子序列
 * abcfbc abfcab 4
 * programming context 2 on
 * abc def 0
 *
 * Created by samwang on 2017/12/20.
 */
public class MaxLenCommonSequence {
    public static void main(String[] args) {
        System.out.println(maxLen("abcfbc","abfcab"));
        System.out.println(maxLen("programming","context"));
        System.out.println(maxLen("abc","def"));
    }

    public static int maxLen(String s1, String s2) {
        int[][] maxLens = new int[s1.length()+1][s2.length()+1];//表示s1的前i个与s2的前j个中最大公共子序列的长度

        for (int i = 0; i <= s1.length(); i++) {
            for (int j = 0; j <= s2.length(); j++) {
                if (i == 0 || j == 0) {
                    maxLens[i][j] = 0;
                } else {
                    if (s1.charAt(i-1) == s2.charAt(j-1)) {
                        maxLens[i][j] = maxLens[i - 1][j - 1] + 1;
                    } else {
                        maxLens[i][j] = Math.max(maxLens[i - 1][j], maxLens[i][j - 1]);
                    }
                }

            }
        }
        return maxLens[s1.length()][s2.length()];
    }

}
